<template>
	<view class="container">
		<!-- 头部导航 -->
		<view class="header">
			<view class="back-btn" @click="goBack">
				<image src="/static/icon-Get-into@3.png" class="back-icon"></image>
			</view>
			<text class="page-title">{{ isPreview ? '预览保单信息' : '填写保单信息' }}</text>
		</view>

		<!-- 表单内容 -->
		<view class="form-wrapper">
			<!-- 基本信息 -->
			<view class="form-section">
				<view class="form-item">
					<text class="required">*</text>
					<text class="label">姓名:</text>
					<input 
						v-model="formData.myname" 
						:disabled="isPreview"
						class="input" 
						placeholder="请输入姓名" 
					/>
				</view>
				<view class="form-item">
					<text class="required">*</text>
					<text class="label">身份证号:</text>
					<input 
						v-model="formData.idcardNum" 
						:disabled="isPreview"
						class="input" 
						placeholder="请输入身份证号" 
					/>
				</view>
				<view class="form-item">
					<text class="required">*</text>
					<text class="label">卡号:</text>
					<input 
						v-model="formData.cardId" 
						:disabled="isPreview"
						class="input" 
						placeholder="请输入卡号" 
					/>
				</view>
			</view>

			<!-- 联系信息 -->
			<view class="form-section">
				<view class="form-item">
					<text class="required">*</text>
					<text class="label">手机号:</text>
					<input 
						v-model="formData.phoneNum" 
						:disabled="isPreview"
						class="input" 
						placeholder="请输入手机号" 
					/>
				</view>
				<view class="form-item">
					<text class="required">*</text>
					<text class="label">婚姻情况:</text>
					<view class="radio-group">
						<view 
							class="radio-item" 
							:class="{ 'active': formData.is_marry === '1' }"
							@click="!isPreview && selectMarriage('1')"
						>
							<text>未婚</text>
						</view>
						<view 
							class="radio-item" 
							:class="{ 'active': formData.is_marry === '2' }"
							@click="!isPreview && selectMarriage('2')"
						>
							<text>已婚</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 地址信息 -->
			<view class="form-section">
				<view class="form-item">
					<text class="required">*</text>
					<text class="label">户籍地址:</text>
					<input 
						v-model="formData.P_address" 
						:disabled="isPreview"
						class="input" 
						placeholder="请输入您的户籍地址" 
					/>
				</view>
				<view class="form-item">
					<text class="required">*</text>
					<text class="label">现居地址:</text>
					<input 
						v-model="formData.N_address" 
						:disabled="isPreview"
						class="input" 
						placeholder="请选择" 
						readonly
						@click="!isPreview && showAreaPicker()"
					/>
				</view>
				<view class="form-item">
					<text class="required">*</text>
					<text class="label">详细地址:</text>
					<input 
						v-model="formData.D_address" 
						:disabled="isPreview"
						class="input" 
						placeholder="请输入您的详细地址" 
					/>
				</view>
			</view>

			<!-- 身份证照片 -->
			<view class="photo-section">
				<view class="section-title">
					<text class="required">*</text>
					<text>手持身份证拍照</text>
				</view>
				<view class="photo-group">
					<view class="photo-item" @click="!isPreview && chooseImage('idfront')">
						<image 
							:src="formData.idfront || '/static/icon-sfz(fan)@2x.png'" 
							class="photo-img"
							:class="{ 'uploaded': formData.idfront }"
						></image>
						<text class="photo-label">身份证正面</text>
					</view>
					<view class="photo-item" @click="!isPreview && chooseImage('idback')">
						<image 
							:src="formData.idback || '/static/icon-sfz(zheng)@2x.png'" 
							class="photo-img"
							:class="{ 'uploaded': formData.idback }"
						></image>
						<text class="photo-label">身份证反面</text>
					</view>
				</view>
			</view>

			<!-- 电子签名 -->
			<view class="signature-section">
				<view class="section-title">
					<text class="required">*</text>
					<text>本人签名</text>
				</view>
				<view class="signature-box" @click="!isPreview && showSignature()">
					<view v-if="!formData.nameP" class="signature-placeholder">点击签名</view>
					<image v-else :src="formData.nameP" class="signature-img"></image>
				</view>
			</view>

			<!-- 申请日期 -->
			<view class="date-section">
				<text>申请日期：</text>
				<text class="date-text">{{ currentDate }}</text>
			</view>

			<!-- 协议 -->
			<view class="agreement-section">
				<view class="agreement-checkbox" @click="toggleAgreement">
					<image 
						:src="isAgreed ? '/static/icon-dui.png' : '/static/check.png'" 
						class="checkbox-icon"
					></image>
				</view>
				<text class="agreement-text">
					本人承诺，以上所填信息均属实，所提供的相关资料均真实、有效，如有虚假，愿意承担一切责任。
				</text>
			</view>

			<!-- 底部按钮 -->
			<view class="button-group">
				<button 
					v-if="!isPreview" 
					class="preview-btn" 
					@click="previewForm"
				>
					预览
				</button>
				<button 
					v-if="isPreview" 
					class="edit-btn" 
					@click="editForm"
				>
					返回编辑
				</button>
				<button 
					class="submit-btn" 
					@click="submitForm"
				>
					{{ isPreview ? '确认提交' : '提交' }}
				</button>
			</view>
		</view>

		<!-- 地区选择器 -->
		<uni-popup ref="areaPicker" type="bottom">
			<view class="picker-container">
				<view class="picker-header">
					<text class="picker-cancel" @click="cancelAreaPicker">取消</text>
					<text class="picker-title">地区选择</text>
					<text class="picker-confirm" @click="confirmAreaPicker">确定</text>
				</view>
				<picker-view 
					:value="areaPickerValue" 
					@change="onAreaPickerChange"
					class="picker-view"
				>
					<picker-view-column>
						<view v-for="(province, index) in provinces" :key="index" class="picker-item">
							{{ province.region_name }}
						</view>
					</picker-view-column>
					<picker-view-column>
						<view v-for="(city, index) in cities" :key="index" class="picker-item">
							{{ city.region_name }}
						</view>
					</picker-view-column>
					<picker-view-column>
						<view v-for="(district, index) in districts" :key="index" class="picker-item">
							{{ district.region_name }}
						</view>
					</picker-view-column>
				</picker-view>
			</view>
		</uni-popup>

		<!-- 电子签名弹窗 -->
		<uni-popup ref="signaturePopup" type="center">
			<view class="signature-popup">
				<view class="signature-header">
					<text class="signature-title">电子签名</text>
					<text class="signature-close" @click="closeSignature">×</text>
				</view>
				<canvas 
					canvas-id="signatureCanvas" 
					class="signature-canvas"
					@touchstart="touchStart"
					@touchmove="touchMove"
					@touchend="touchEnd"
				></canvas>
				<view class="signature-buttons">
					<button class="clear-btn" @click="clearSignature">清除</button>
					<button class="save-btn" @click="saveSignature">完成</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import { identityApi, commonApi } from '@/api/index.js'
import { getToken, getCurrentUser } from '@/api/auth.js'

export default {
	data() {
		return {
			isPreview: false,
			isAgreed: false,
			currentDate: '',
			formData: {
				myname: '',
				idcardNum: '',
				cardId: '',
				phoneNum: '',
				is_marry: '1',
				P_address: '',
				N_address: '',
				D_address: '',
				idfront: '',
				idback: '',
				nameP: ''
			},
			// 地区选择相关
			provinces: [],
			cities: [],
			districts: [],
			areaPickerValue: [0, 0, 0],
			selectedAreaData: null,
			// 签名相关
			canvasContext: null,
			isDrawing: false,
			lastPoint: null
		}
	},
	
	onLoad() {
		this.initPage()
	},
	
	methods: {
		// 初始化页面
		async initPage() {
			this.setCurrentDate()
			await this.loadUserInfo()
			await this.loadRegionData()
		},
		
		// 设置当前日期
		setCurrentDate() {
			const date = new Date()
			const year = date.getFullYear()
			const month = String(date.getMonth() + 1).padStart(2, '0')
			const day = String(date.getDate()).padStart(2, '0')
			const hours = String(date.getHours()).padStart(2, '0')
			const minutes = String(date.getMinutes()).padStart(2, '0')
			const seconds = String(date.getSeconds()).padStart(2, '0')
			this.currentDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
		},
		
		// 加载用户信息
		async loadUserInfo() {
			try {
				const res = await identityApi.getIdentityInfo()
				if (res.r === 0) {
					const data = res.data
					this.formData.myname = data.realname || ''
					this.formData.idcardNum = data.id_number || ''
					this.formData.cardId = data.card_num || ''
					
					const userInfo = getCurrentUser()
					this.formData.phoneNum = userInfo.phone || ''
				}
			} catch (error) {
				console.error('加载用户信息失败:', error)
			}
		},
		
		// 加载地区数据
		async loadRegionData() {
			try {
				const res = await commonApi.getAllRegion()
				if (res.r === 0) {
					this.provinces = res.data.gr || []
					if (this.provinces.length > 0) {
						this.cities = this.provinces[0].child || []
						if (this.cities.length > 0) {
							this.districts = this.cities[0].child || []
						}
					}
				}
			} catch (error) {
				console.error('加载地区数据失败:', error)
			}
		},
		
		// 选择婚姻状况
		selectMarriage(status) {
			this.formData.is_marry = status
		},
		
		// 显示地区选择器
		showAreaPicker() {
			this.$refs.areaPicker.open()
		},
		
		// 地区选择器变化
		onAreaPickerChange(e) {
			const values = e.detail.value
			this.areaPickerValue = values
			
			// 更新城市列表
			if (this.provinces[values[0]]) {
				this.cities = this.provinces[values[0]].child || []
				// 如果当前选中的城市索引超出范围，重置为0
				if (values[1] >= this.cities.length) {
					this.areaPickerValue[1] = 0
				}
			}
			
			// 更新区县列表
			if (this.cities[this.areaPickerValue[1]]) {
				this.districts = this.cities[this.areaPickerValue[1]].child || []
				// 如果当前选中的区县索引超出范围，重置为0
				if (values[2] >= this.districts.length) {
					this.areaPickerValue[2] = 0
				}
			}
		},
		
		// 确认地区选择
		confirmAreaPicker() {
			const [provinceIndex, cityIndex, districtIndex] = this.areaPickerValue
			const province = this.provinces[provinceIndex]
			const city = this.cities[cityIndex]
			const district = this.districts[districtIndex]
			
			if (province && city && district) {
				this.formData.N_address = `${province.region_name}-${city.region_name}-${district.region_name}`
				this.selectedAreaData = { province, city, district }
			}
			
			this.$refs.areaPicker.close()
		},
		
		// 取消地区选择
		cancelAreaPicker() {
			this.$refs.areaPicker.close()
		},
		
		// 选择图片
		chooseImage(type) {
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['camera', 'album'],
				success: (res) => {
					this.uploadImage(res.tempFilePaths[0], type)
				}
			})
		},
		
		// 上传图片
		uploadImage(filePath, type) {
			uni.showLoading({ title: '上传中...' })
			
			uni.uploadFile({
				url: this.$config.baseUrl + 'home/common/upload_img',
				filePath: filePath,
				name: 'file',
				header: {
					'token': getToken()
				},
				success: (res) => {
					try {
						const result = JSON.parse(res.data)
						if (result.r === 0) {
							this.formData[type] = this.$config.imgUrl + result.data
						} else {
							uni.showToast({
								title: result.msg || '上传失败',
								icon: 'none'
							})
						}
					} catch (error) {
						uni.showToast({
							title: '上传失败',
							icon: 'none'
						})
					}
				},
				fail: () => {
					uni.showToast({
						title: '上传失败',
						icon: 'none'
					})
				},
				complete: () => {
					uni.hideLoading()
				}
			})
		},
		
		// 显示签名弹窗
		showSignature() {
			this.$refs.signaturePopup.open()
			this.$nextTick(() => {
				this.initCanvas()
			})
		},
		
		// 初始化画布
		initCanvas() {
			this.canvasContext = uni.createCanvasContext('signatureCanvas', this)
			this.canvasContext.setStrokeStyle('#000000')
			this.canvasContext.setLineWidth(4)
			this.canvasContext.setLineCap('round')
			this.canvasContext.setLineJoin('round')
		},
		
		// 触摸开始
		touchStart(e) {
			this.isDrawing = true
			this.lastPoint = {
				x: e.touches[0].x,
				y: e.touches[0].y
			}
		},
		
		// 触摸移动
		touchMove(e) {
			if (!this.isDrawing) return
			
			const currentPoint = {
				x: e.touches[0].x,
				y: e.touches[0].y
			}
			
			this.canvasContext.beginPath()
			this.canvasContext.moveTo(this.lastPoint.x, this.lastPoint.y)
			this.canvasContext.lineTo(currentPoint.x, currentPoint.y)
			this.canvasContext.stroke()
			this.canvasContext.draw(true)
			
			this.lastPoint = currentPoint
		},
		
		// 触摸结束
		touchEnd() {
			this.isDrawing = false
		},
		
		// 清除签名
		clearSignature() {
			this.canvasContext.clearRect(0, 0, 300, 200)
			this.canvasContext.draw()
		},
		
		// 保存签名
		saveSignature() {
			uni.canvasToTempFilePath({
				canvasId: 'signatureCanvas',
				success: (res) => {
					this.uploadSignature(res.tempFilePath)
				}
			}, this)
		},
		
		// 上传签名
		uploadSignature(filePath) {
			uni.showLoading({ title: '保存中...' })
			
			uni.uploadFile({
				url: this.$config.baseUrl + 'home/common/upload_img',
				filePath: filePath,
				name: 'file',
				header: {
					'token': getToken()
				},
				success: (res) => {
					try {
						const result = JSON.parse(res.data)
						if (result.r === 0) {
							this.formData.nameP = this.$config.imgUrl + result.data
							this.closeSignature()
						} else {
							uni.showToast({
								title: result.msg || '保存失败',
								icon: 'none'
							})
						}
					} catch (error) {
						uni.showToast({
							title: '保存失败',
							icon: 'none'
						})
					}
				},
				fail: () => {
					uni.showToast({
						title: '保存失败',
						icon: 'none'
					})
				},
				complete: () => {
					uni.hideLoading()
				}
			})
		},
		
		// 关闭签名弹窗
		closeSignature() {
			this.$refs.signaturePopup.close()
		},
		
		// 切换协议同意状态
		toggleAgreement() {
			this.isAgreed = !this.isAgreed
		},
		
		// 预览表单
		previewForm() {
			this.isPreview = true
		},
		
		// 编辑表单
		editForm() {
			this.isPreview = false
		},
		
		// 表单验证
		validateForm() {
			if (!this.formData.myname.trim()) {
				uni.showToast({ title: '真实姓名不可为空', icon: 'none' })
				return false
			}
			
			if (!this.formData.idcardNum.trim()) {
				uni.showToast({ title: '身份证号码不可为空', icon: 'none' })
				return false
			}
			
			if (!this.formData.cardId.trim()) {
				uni.showToast({ title: '卡号不可为空', icon: 'none' })
				return false
			}
			
			if (!this.formData.phoneNum.trim()) {
				uni.showToast({ title: '手机号不可为空', icon: 'none' })
				return false
			}
			
			const phoneReg = /^1[0-9]\d{9}$/
			if (!phoneReg.test(this.formData.phoneNum)) {
				uni.showToast({ title: '手机号格式错误', icon: 'none' })
				return false
			}
			
			if (!this.formData.P_address.trim()) {
				uni.showToast({ title: '户籍地址不可为空', icon: 'none' })
				return false
			}
			
			if (!this.formData.N_address.trim()) {
				uni.showToast({ title: '现居地址不可为空', icon: 'none' })
				return false
			}
			
			if (!this.formData.D_address.trim()) {
				uni.showToast({ title: '详细地址不可为空', icon: 'none' })
				return false
			}
			
			if (!this.formData.idfront) {
				uni.showToast({ title: '请上传身份证正面照', icon: 'none' })
				return false
			}
			
			if (!this.formData.idback) {
				uni.showToast({ title: '请上传身份证背面照', icon: 'none' })
				return false
			}
			
			if (!this.formData.nameP) {
				uni.showToast({ title: '请填写电子签名', icon: 'none' })
				return false
			}
			
			if (!this.isAgreed) {
				uni.showToast({ title: '请点击阅读同意优享优品平台市运营协议', icon: 'none' })
				return false
			}
			
			return true
		},
		
		// 提交表单
		async submitForm() {
			if (!this.validateForm()) return
			
			try {
				uni.showLoading({ title: '提交中...' })
				
				const recordId = uni.getStorageSync('record_id')
				
				const submitData = {
					insurant_realname: this.formData.myname,
					id_number: this.formData.idcardNum,
					phone: this.formData.phoneNum,
					card_num: this.formData.cardId,
					sign_url: this.extractPath(this.formData.nameP),
					front_photo: this.extractPath(this.formData.idfront),
					back_photo: this.extractPath(this.formData.idback),
					marital_state: parseInt(this.formData.is_marry),
					location_address: this.formData.N_address + this.formData.D_address,
					domicile_address: this.formData.P_address,
					record_id: parseInt(recordId)
				}
				
				const res = await identityApi.addInsuranceInfo(submitData)
				
				if (res.r === 0) {
					uni.removeStorageSync('record_id')
					uni.showToast({
						title: res.msg || '提交成功',
						icon: 'success'
					})
					
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/identity/shenqing_more'
						})
					}, 2000)
				} else {
					uni.showToast({
						title: res.msg || '提交失败',
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('提交失败:', error)
				uni.showToast({
					title: '提交失败',
					icon: 'none'
				})
			} finally {
				uni.hideLoading()
			}
		},
		
		// 提取文件路径
		extractPath(url) {
			if (!url) return ''
			const tmpIndex = url.indexOf('tmp')
			return tmpIndex !== -1 ? url.slice(tmpIndex) : url
		},
		
		// 返回上一页
		goBack() {
			uni.navigateBack()
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	background-color: #eeeeee;
}

.header {
	display: flex;
	align-items: center;
	height: 88rpx;
	background-color: #fff;
	padding: 0 30rpx;
	position: relative;
	
	.back-btn {
		position: absolute;
		left: 30rpx;
		
		.back-icon {
			width: 40rpx;
			height: 40rpx;
		}
	}
	
	.page-title {
		flex: 1;
		text-align: center;
		font-size: 36rpx;
		font-weight: 500;
	}
}

.form-wrapper {
	padding: 20rpx;
}

.form-section {
	background-color: #fff;
	margin-bottom: 20rpx;
	border-top: 2rpx solid #e3e3e3;
	
	.form-item {
		display: flex;
		align-items: center;
		height: 90rpx;
		padding: 0 30rpx;
		border-bottom: 2rpx solid #e3e3e3;
		
		&:last-child {
			border-bottom: none;
		}
		
		.required {
			color: #ff2e00;
			margin-right: 16rpx;
		}
		
		.label {
			font-size: 28rpx;
			margin-right: 20rpx;
			min-width: 140rpx;
		}
		
		.input {
			flex: 1;
			height: 90rpx;
			line-height: 90rpx;
			font-size: 28rpx;
			padding: 0 20rpx;
		}
		
		.radio-group {
			display: flex;
			flex: 1;
			
			.radio-item {
				display: flex;
				align-items: center;
				height: 90rpx;
				padding-left: 68rpx;
				margin-left: 60rpx;
				background: url('/static/radio.png') no-repeat left center;
				background-size: 44rpx 44rpx;
				font-size: 28rpx;
				
				&.active {
					background-image: url('/static/radio-checked.png');
				}
				
				&:first-child {
					margin-left: 100rpx;
				}
			}
		}
	}
}

.photo-section {
	background-color: #fff;
	padding: 30rpx;
	margin-bottom: 20rpx;
	
	.section-title {
		font-size: 30rpx;
		margin-bottom: 30rpx;
		
		.required {
			color: #ff2e00;
			margin-right: 16rpx;
		}
	}
	
	.photo-group {
		display: flex;
		justify-content: space-between;
		
		.photo-item {
			width: 305rpx;
			text-align: center;
			
			.photo-img {
				width: 305rpx;
				height: 193rpx;
				border-radius: 8rpx;
				
				&.uploaded {
					border: 2rpx solid #1e83d3;
				}
			}
			
			.photo-label {
				display: block;
				font-size: 26rpx;
				color: #666;
				margin-top: 10rpx;
			}
		}
	}
}

.signature-section {
	background-color: #fff;
	padding: 30rpx;
	margin-bottom: 20rpx;
	
	.section-title {
		font-size: 30rpx;
		margin-bottom: 30rpx;
		
		.required {
			color: #ff2e00;
			margin-right: 16rpx;
		}
	}
	
	.signature-box {
		width: 100%;
		height: 192rpx;
		border: 2rpx solid #eee;
		border-radius: 8rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
		
		.signature-placeholder {
			color: #ccc;
			font-size: 30rpx;
		}
		
		.signature-img {
			width: 100%;
			height: 100%;
			border-radius: 6rpx;
		}
	}
}

.date-section {
	background-color: #fff;
	padding: 30rpx;
	margin-bottom: 20rpx;
	font-size: 28rpx;
	
	.date-text {
		color: #9f9f9f;
		margin-left: 20rpx;
	}
}

.agreement-section {
	display: flex;
	align-items: flex-start;
	padding: 30rpx;
	margin-bottom: 20rpx;
	
	.agreement-checkbox {
		margin-right: 30rpx;
		margin-top: 10rpx;
		
		.checkbox-icon {
			width: 50rpx;
			height: 50rpx;
		}
	}
	
	.agreement-text {
		flex: 1;
		font-size: 25rpx;
		color: #9f9f9f;
		line-height: 1.6;
	}
}

.button-group {
	display: flex;
	padding: 0 20rpx;
	margin-bottom: 40rpx;
	
	button {
		flex: 1;
		height: 90rpx;
		line-height: 90rpx;
		text-align: center;
		border-radius: 20rpx;
		font-size: 34rpx;
		border: none;
		
		&:first-child {
			margin-right: 20rpx;
		}
	}
	
	.preview-btn {
		background-color: #ff9500;
		color: #fff;
	}
	
	.edit-btn {
		background-color: #6fb6fd;
		color: #fff;
	}
	
	.submit-btn {
		background-color: #ff2e00;
		color: #fff;
	}
}

// 地区选择器样式
.picker-container {
	background-color: #fff;
	border-radius: 20rpx 20rpx 0 0;
	
	.picker-header {
		display: flex;
		align-items: center;
		height: 80rpx;
		padding: 0 40rpx;
		border-bottom: 2rpx solid #dcdcdc;
		position: relative;
		
		.picker-cancel {
			color: #666;
			font-size: 30rpx;
		}
		
		.picker-title {
			position: absolute;
			left: 50%;
			transform: translateX(-50%);
			font-size: 30rpx;
			font-weight: 500;
		}
		
		.picker-confirm {
			color: #1e83d3;
			font-size: 30rpx;
		}
	}
	
	.picker-view {
		height: 400rpx;
		
		.picker-item {
			display: flex;
			align-items: center;
			justify-content: center;
			height: 80rpx;
			font-size: 30rpx;
		}
	}
}

// 电子签名弹窗样式
.signature-popup {
	width: 600rpx;
	height: 500rpx;
	background-color: #fff;
	border-radius: 20rpx;
	overflow: hidden;
	
	.signature-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 80rpx;
		padding: 0 30rpx;
		border-bottom: 2rpx solid #eee;
		
		.signature-title {
			font-size: 32rpx;
			font-weight: 500;
		}
		
		.signature-close {
			font-size: 40rpx;
			color: #999;
		}
	}
	
	.signature-canvas {
		width: 600rpx;
		height: 340rpx;
		background-color: #fff;
	}
	
	.signature-buttons {
		display: flex;
		height: 80rpx;
		
		button {
			flex: 1;
			height: 100%;
			border: none;
			font-size: 30rpx;
			
			&.clear-btn {
				background-color: #fe9402;
				color: #fff;
			}
			
			&.save-btn {
				background-color: #ff3e0b;
				color: #fff;
			}
		}
	}
}

// 禁用状态样式
input:disabled {
	background-color: #f5f5f5 !important;
	color: #999 !important;
}
</style>